<template>
  <div class="">
    <PageTitle :title="pageTitle"></PageTitle>
    <div class="form-wrapper">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="商品名称" prop="title">
          <el-input v-model="ruleForm.title" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="ruleForm.price" type="number" placeholder="请输入商品价格">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品描述" prop="describe">
          <el-input v-model="ruleForm.describe" placeholder="请输入商品描述"></el-input>
        </el-form-item>
        <el-form-item label="商品库存" prop="Stock">
          <el-input v-model="ruleForm.Stock" type="number" placeholder="请输入商品库存"></el-input>
        </el-form-item>
        <el-form-item label="标题图片" prop="titleFileList">
          <el-upload
            accept=".png, .jpeg, .jpg"
            :action="$api + '/v1/upload/image'"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :on-success="titleFileSuccess"
            :auto-upload="true"
            :file-list="ruleForm.titleFileList"
            :limit="titleFileMaxCount"
            :class="{'hide': titleFileToLarge}"
            name="name"
          >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url"
                >
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemoveTitle(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品图片" prop="fileList">
          <el-upload
            accept=".png, .jpeg, .jpg"
            :action="$api + '/v1/upload/image'"
            list-type="picture-card"
            :before-upload="beforeUpload"
            :on-success="fileSuccess"
            :auto-upload="true"
            :file-list="ruleForm.fileList"
            :limit="fileListMaxCount"
            :class="{hide: fileToLarge}"
            name="name"
          >
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{file}">
                <img
                  class="el-upload-list__item-thumbnail"
                  :src="file.url" alt=""
                >
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreview(file)"
                  >
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="!disabled"
                    class="el-upload-list__item-delete"
                    @click="handleRemove(file)"
                  >
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品详情" prop="details">
          <TinymceEditor @onChange="editorChange" :value="ruleForm.details"></TinymceEditor>
        </el-form-item>
        <el-form-item label="商品状态" prop="state">
          <el-select v-model="ruleForm.state" placeholder="前选择商品状态">
            <el-option label="上架" value="0"></el-option>
            <el-option label="下架" value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="goodstype_id">
          <el-select v-model="ruleForm.goodstype_id" placeholder="请选择商品类别">
            <template v-for="item in goodsTypesArr">
              <el-option :label="item.class_name" :value="item.id" :key="item.id"></el-option>
            </template>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
          <el-button @click="$router.go(-1)">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  import _ from 'lodash'
  import PageTitle from '@/components/pageTitle/PageTitle.vue'
  import TinymceEditor from '@/components/tinymceEditor/TinymceEditor.vue'
  export default {
    name: 'brandDealerGoodsDetail',
    components: {
      PageTitle,
      TinymceEditor
    },
    async mounted() {
      try{
        let {data: {data}} = await this.$axios({
          url: '/v1/fication/frame',
          method: 'GET',
          params: {
            size: 100,
            current: 1,
            state: 2
          }
        })
        this.goodsTypesArr = data.items
      }catch(e){
        this.$message({
          type: 'error',
          message: e
        })
      }
      
      if(this.$route.params.id != 'none') {
        this._get()
      }
    },
    data() {
      return {
        title: '',
        goodsTypesArr: [],
        ruleForm: {
          title: '',
          price: '',
          describe: '',
          Stock: '',
          details: '',
          state: '',
          goodstype_id: '',
          titleFileList: [],
          fileList: []
        },
        rules: {
          title: [
            { required: true, message: '请输入商品名称', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入商品价格', trigger: 'blur' },
            {
              validator(rule, value, callback) {
                const boolean = new RegExp(/^([1-9]\d{0,8}|0)(\.\d{1,2})?$/).test(value)
                if(!boolean) {
                  return callback(new Error('请正确输入商品价格'))
                }
                return callback()
              },
              trigger: 'blur'
            }
          ],
          describe: [
            { required: true, message: '请输入商品描述', trigger: 'blur' }
          ],
          Stock: [
            { required: true, message: '请输入商品库存', trigger: 'blur' },
            {
              validator(rule, value, callback) {
                const boolean = new RegExp(/^[1-9][0-9]*$/).test(value)
                if (!boolean) {
                    return callback(new Error('请输入正整数'))
                }
                return callback()
              },
              trigger: 'blur'
            }
          ],
          details: [
            { required: true, message: '请编辑商品描述', trigger: 'blur' }
          ],
          state: [
            { required: true, message: '请选择商品状态', trigger: 'change' }
          ],
          goodstype_id: [
            { required: true, message: '请选择商品类型', trigger: 'change' }
          ],
          fileList: [
            { type: 'array', required: true, message: '请上传商品图片' }
          ],
          titleFileList: [
            { type: 'array', required: true, message: '请上传标题图片' }
          ]
        },
        dialogImageUrl: '',
        dialogVisible: false,
        disabled: false,
        titleFileMaxCount: 1,
        fileListMaxCount: 5
      };
    },
    computed: {
      pageTitle() {
        return this.$route.params.id == 'none' ? '商品添加' : '商品详情'
      },
      submitUrl() {
        return this.$route.params.id == 'none' ? '/v1/goods/add' : '/v1/goods/modify'
      },
      titleFileToLarge() {
        return this.ruleForm.titleFileList.length >= this.titleFileMaxCount
      },
      fileToLarge() {
        return this.ruleForm.fileList.length >= this.fileListMaxCount
      },
      titleFileIdArr() {
        return this.ruleForm.titleFileList[0].id
      },
      fileIdArr() {
        return this.ruleForm.fileList.map((item) => {
          return item.id
        }).toString()
      }
    },
    methods: {
      // 监听富文本组件的自定义事件
      editorChange(e, data) {
        this.ruleForm.details = data
      },
      // 重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields()
      },
      // 上传图片的格式和大小验证
      beforeUpload(file) {
        const isJPG = file.type === 'image/jpeg' || file.type === 'image/jpg' || file.type === 'image/png'
        const isLt10M = file.size / 1024 / 1024 < 10

        if (!isJPG) {
          this.$message.warning('上传头像图片只能是 JPG | PNG 格式!')
        }
        if (!isLt10M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isJPG && isLt10M
      },
      // 删除图片的事件
      handleRemove(file) {
        this.ruleForm.fileList = this.ruleForm.fileList.filter((item) => {
          return file.id !== item.id
        })
      },
      handleRemoveTitle(file) {
        this.ruleForm.titleFileList = this.ruleForm.titleFileList.filter((item) => {
          return file.id !== item.id
        })
      },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      // 上传图片成功的回调
      fileSuccess(r, file) {
        file.id = file.response.data.id
        this.ruleForm.fileList.push({...file})
      },
      titleFileSuccess(r, file) {
        file.id = file.response.data.id
        this.ruleForm.titleFileList.push({...file})
      },
      // 如果是编辑页，请求数据的函数
      async _get() {
        try{
          let {data: {data}} = await this.$axios({
            url: '/v1/goods/show',
            method: 'GET',
            params: {
              id: this.$route.params.id
            }
          })
          this.ruleForm.title = data.items[0].title
          this.ruleForm.price = data.items[0].price
          this.ruleForm.describe = data.items[0].describe
          this.ruleForm.Stock = data.items[0].Stock
          this.ruleForm.details = data.items[0].details
          this.ruleForm.state = data.items[0].state
          this.ruleForm.goodstype_id = data.items[0].goodstype_id
          this.ruleForm.titleFileList.push({
            id: '',
            url: data.items[0].url
          })
          this.ruleForm.fileList = data.a
        }catch(e){
          this.$message({
            type: 'error',
            message: e
          })
        }
      },
      // 提交表单
      submitForm(formName) {
        this.$refs[formName].validate(async valid => {
          if (!valid) {
            return false
          } else {
            this._submit()
          }
        })
      },
      _submit: _.throttle(async function() {
        try{
          let {data: {data, code}} = await this.$axios({
            url: this.submitUrl,
            method: 'POST',
            data:{
              title: this.ruleForm.title,
              price: this.ruleForm.price,
              describe: this.ruleForm.describe,
              Stock: this.ruleForm.Stock,
              details: this.ruleForm.details,
              state: this.ruleForm.state,
              goodstype_id: this.ruleForm.goodstype_id,
              pice: this.titleFileIdArr,
              picture: this.fileIdArr,
              up_id: 1,
              id: this.$route.params.id != 'none' ? this.$route.params.id : ''
            }
          })
          this.$message.success(data)
          if(code == 0) {
            setTimeout(() => {
              this.$router.go(-1)
            }, 2000)
          }
        }catch(e){
          this.$message({
            type: 'error',
            message: e
          })
        }
      }, 2000, {trailing: false})
    }
  }
</script>

<style lang='scss'>
  .form-wrapper {
    width:50%;
  }
  .hide .el-upload--picture-card {
    /* display: none; */
  }
</style>
